package kassiopeia.agent.plugin;

import java.io.PrintWriter;
import java.io.StringWriter;

import kassiopeia.commons.exception.PluginCreationException;
import kassiopeia.commons.model.Coordinates;
import kassiopeia.plugin.Plugin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jmx.export.annotation.ManagedOperation;
import org.springframework.jmx.export.annotation.ManagedOperationParameter;
import org.springframework.jmx.export.annotation.ManagedOperationParameters;
import org.springframework.jmx.export.annotation.ManagedResource;
import org.springframework.stereotype.Component;

@Component
@ManagedResource
public class PluginFactoryMBean {

	@Autowired
	private PluginFactory pluginFactory;

	@ManagedOperation(
			description="Creates plugin instance and says what type is it")
	@ManagedOperationParameters({
		@ManagedOperationParameter(name="groupId", description="Group Identifier"),
		@ManagedOperationParameter(name="pluginId", description="Plugin Identifier"),
		@ManagedOperationParameter(name="version", description="Plugin version")
	})
	public String createPluginInstance(String groupId, String pluginId, String version) {
		try {
			Coordinates coordinates = new Coordinates(groupId, pluginId, version);
			Plugin plugin = pluginFactory.newInstance(coordinates, "sampleInstance");

			return plugin.getClass().getSimpleName();
		} catch(PluginCreationException exception) {
			StringWriter writer = new StringWriter();
			exception.printStackTrace(new PrintWriter(writer));
			return writer.toString();
		}
	}
}
